import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { DrawBoard } from './DrawBoard';
import { ToolBar } from './ToolBar';
import { ImageEditorProvider } from './context';
import type { DrawPalette } from './microPalette/DrawPalette';
import { VIDEO_FIRST_FRAME_BASE64 } from './microPalette/mockData/firstFrameImgBase64';
import { ImageView, MainView, VideoEditorContainer } from './styled';

export interface ImageEditorForwardRef {
  getPaletteInstance: () => DrawPalette | null;
}

export const ImageEditor = forwardRef<ImageEditorForwardRef, any>(
  (props, ref) => {
    const [paletteInstance, setPaletteInstance] = useState<DrawPalette | null>(
      null,
    );
    /** 对外派发Ref 句柄 */
    useImperativeHandle(ref, () => ({
      getPaletteInstance: () => paletteInstance,
    }));

    useEffect(() => {
      return () => {
        paletteInstance?.clear();
      };
    }, []);

    return (
      <ImageEditorProvider value={{ paletteInstance }}>
        <VideoEditorContainer>
          <MainView>
            <DrawBoard initPalateCallback={setPaletteInstance} />
            {/* 为了兼容 EMarkTool.ERASER(橡皮擦功能，画布透明问题)  */}
            <ImageView src={VIDEO_FIRST_FRAME_BASE64} />
          </MainView>
          <ToolBar />
        </VideoEditorContainer>
      </ImageEditorProvider>
    );
  },
);
